package com.madou.dbtool.redis.manager;

import com.madou.inters.util.TipUtils;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

/**
 * @author miukoo
 * Redis多种默认下的管理器
 */
public class RedisSourceManagerFactory {
    private static final Map<String, Jedis> CONNECTION_MAP = new HashMap<>();
    private static Map<String,RedisSourceManager> DATASOURCE_MANAGER  = new HashMap<>();

    /**
     * 最大连接次数
     */
    private static final int maxRetry = 2;

    public static Jedis getConnection(String host,int port,String password) {
        return getConnection(host, port, password,0);
    }

    public static void clearConnection(String host,int port) {
        String id = String.format("%s-%s",host,port);
        CONNECTION_MAP.remove(id);
    }

    /**
     * 获取连接，并最多获取三次
     * @param count
     * @return
     */
    private static Jedis getConnection(String host,int port,String password, int count) {
        if(count>maxRetry) {
            return null;
        }
        String id = String.format("%s-%s",host,port);
        Jedis connection = CONNECTION_MAP.get(id);
        if(connection==null||!connection.isConnected()) {
            try {
                connection = new Jedis(host, port);
                if (password != null && password != "") {
                    connection.auth(password);
                }
                connection.info();
            } catch (Exception e) {
                if(count==maxRetry){
                    TipUtils.showErrorDialog("获取数据库连接失败："+e.getMessage(),"Tips");
                }else if(count<maxRetry) {
                    return getConnection(host, port,password,count+1);
                }
            }
        }
        CONNECTION_MAP.put(id,connection);
        return connection;
    }

    /**
     * 获取一个数据源
     * @param name
     * @return
     */
    public static RedisSourceManager getDataSourceManager(String name){
        return DATASOURCE_MANAGER.get(name);
    }

    /**
     * 注册数据源信息
     * @param dataSourceName
     * @param dataSourceManager
     */
    public static void setDataSourceManager(String dataSourceName, RedisSourceManager dataSourceManager) {
        DATASOURCE_MANAGER.put(dataSourceName,dataSourceManager);
    }
}
